const request = require('request');
const ImageInfo = require('./image_info');

class BingWallpaper {

    constructor() {
        this.pageSize = 12;
        this.categoryList = [
            {
                "cid" : "",
                "name" : "每日精选"
            },
        ]
    }

    getCategoryList() {
        return this.categoryList;
    }

    getHtml (pageNo) {
        let url = `https://bing.ioliu.cn/?p=${pageNo}`;
        return new Promise(function(reslove, reject) {
            request({
                url: url,
                method: "GET",
                headers: {
                    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
                    'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7',
                    'Cache-Control': 'max-age=0',
                    'Connection': 'keep-alive',
                    'Host': 'bing.ioliu.cn',
                    'Referer': 'https://bing.ioliu.cn/',
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
                },
            }, function(error, response, body) {
                if (!error && response.statusCode == 200) {
                    reslove({'response':response, 'body': body});
                } else {
                    reject(error);
                }
            })
        });
    }

    async getList(pageNo = 1, cid = '') {
        let imageList = [];
        let result = await this.getHtml(pageNo);
        if (result.body.length <= 0) {
            return {};
        }
        let html = result.body;
        let reg = /<div[^<>]*class="item">[\s\S]*?class="options">[\s\S]*?<\/div>/ig;
        let matched = html.match(reg);
        if (!matched) {
            return [];
        }

        for ( let i in matched) {
            let imgInfo = new ImageInfo();
            let imgUrl = /<img[^<>]*src="([^<>]*)"/i.exec(matched[i]);
            let desc = /description[^<>]*>\s*<h3>([^<>]*)<\/h3>/i.exec(matched[i]);
            if (desc && desc[1].length >= 0) {
                imgInfo.setDesc(desc[1]);
            }
            let date = /calendar[\s\S]*?<em[^<>]*class="t"[^<>]*>([^<>]*?)<\/em>/i.exec(matched[i]);
            if (date && date[1].length >= 0) {
                imgInfo.setDate(date[1]);
            }
            let hot = /view[\s\S]*?<em[^<>]*class="t"[^<>]*>([^<>]*?)<\/em>/i.exec(matched[i]);
            if (hot && hot[1].length >= 0) {
                imgInfo.setHot(hot[1]);
            }
            if (!imgUrl || imgUrl[1].length <= 0) {
                continue;
            }
            imgInfo.setUrl(imgUrl[1]);
            imageList.push(imgInfo)
        }
        return imageList;

    }

    getPageSize() {
        return this.pageSize;
    }
}

module.exports = BingWallpaper;
